/**
 * Created by shaoyin.zj on 16/12/25.
 */

var ws = new WebSocket("ws://"+window.location.hostname+":3001");
ws.onopen = function (e) {
    console.log('Connection to server opened');
}

// 接收服务端主动发过来的消息
ws.onmessage = function(evt){
	var received_msg = evt.data;
	var newItem = '<div class="line robot">'+
						'<div><i class="icon-user-md"></i></div>'+
						'<div class="talk-content">'+received_msg+'</div>'+
					'</div>';
	$('#talk-list').append(newItem);
	$('body').scrollTop($('body')[0].scrollHeight);
}


// 发送用户信息到服务端
function sendTalk(){
 	var userInput = $('.talk-input').val();
	if(userInput){
		var newItem = '<div class="line user">'+
							'<div><i class="icon-user-md"></i></div>'+
							'<div class="talk-content">'+userInput+'</div>'+
						'</div>';
		$('#talk-list').append(newItem);
		$('body').scrollTop($('body')[0].scrollHeight);
		$('.talk-input').val('');
		ws.send(userInput);
		console.log('websocket send:' + userInput);
	}
}

document.onkeydown = function(e){
  var keycode = document.all?event.keyCode:e.which;
  if(keycode == 13){
  	sendTalk();
  }
}